use config::{Config, File, Environment};
use serde::Deserialize;
use std::path::PathBuf;

#[derive(Debug, Deserialize)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub grpc_workers: usize,
    pub http_port: u16,
}

#[derive(Debug, Deserialize)]
pub struct StorageConfig {
    pub storage_type: String,
    pub buffer_size: usize,
    pub flush_interval: u64,
    pub elastic: ElasticConfig,
    pub database: DatabaseConfig,
}

#[derive(Debug, Deserialize)]
pub struct ElasticConfig {
    pub url: String,
    pub index_prefix: String,
    pub username: String,
    pub password: String,
    pub bulk_size: usize,
}

#[derive(Debug, Deserialize)]
pub struct DatabaseConfig {
    pub url: String,
    pub pool_size: u32,
    pub max_lifetime: u64,
}

pub fn load_config() -> Result<Config, config::ConfigError> {
    let config_path = std::env::var("LOG_CONFIG_PATH")
        .unwrap_or_else(|_| "config/default.toml".to_string());
    
    let config = Config::builder()
        .add_source(File::with_name(&config_path))
        .add_source(Environment::with_prefix("LOG").separator("_"))
        .build()?;
    
    config.try_deserialize()
}